package com.clip.util;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Struts2Utils {
	private static final String ENCODING_PREFIX = "encoding:";
	private static final String NOCACHE_PREFIX = "no-cache:";
	private static final String ENCODING_DEFAULT = "UTF-8";
	private static final boolean NOCACHE_DEFAULT = true;
	private static Logger logger = LoggerFactory.getLogger(Struts2Utils.class);
	private Struts2Utils() {
	}
	
	public static HttpSession getSession() {
		return ServletActionContext.getRequest().getSession();
	}
	
	public static HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	
	public static HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}
	
	public static ServletContext getServletContext() {
		return ServletActionContext.getServletContext();
	}
	
	public static void render(final String contentType, final String content, final String... headers) {
		try {
			String encoding = ENCODING_DEFAULT;
			boolean noCache = NOCACHE_DEFAULT;
			for (String header : headers) {
				String headerName = StringUtils.substringBefore(header, ":");
				String headerValue = StringUtils.substringAfter(header, ":");

				if (StringUtils.equalsIgnoreCase(headerName, ENCODING_PREFIX)) {
					encoding = headerValue;
				} else if (StringUtils.equalsIgnoreCase(headerName, NOCACHE_PREFIX)) {
					noCache = Boolean.parseBoolean(headerValue);
				} else
					throw new IllegalArgumentException(headerName + "head err");
			}

			HttpServletResponse response = ServletActionContext.getResponse();

			String fullContentType = contentType + ";charset=" + encoding;
			response.setContentType(fullContentType);
			if (noCache) {
				response.setHeader("Pragma", "No-cache");
				response.setHeader("Cache-Control", "no-cache");
				response.setDateHeader("Expires", 0);
			}

			response.getWriter().write(content);

		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	public static void renderText(final String text, final String... headers) {
		render("text/plain", text, headers);
	}
	
	public static void renderHtml(final String html, final String... headers) {
		render("text/html", html, headers);
	}
	
	public static void renderXml(final String xml, final String... headers) {
		render("text/xml", xml, headers);
	}
	
	public static void renderJson(final String string, final String... headers) {
		render("application/json", string, headers);
	}
}
